#encoding=utf-8
'''
Created on 2018-8-9

@author: cooler
'''
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("./")

from catgateio.GateIO import GateIO
from models import *
from utils.Monitor import Monitor

from key import apiKey,secretKey

import logging.handlers
import logging,time

logger = logging.getLogger()   
logfile = logging.handlers.TimedRotatingFileHandler(os.path.join(os.getcwd(), "logs/tickers"), 'D', 1, 0)
# 设置后缀名称，跟strftime的格式一样
logfile.suffix = "%Y%m%d.log"
logger.addHandler(logfile) 
#set formater  
#formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") 
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s")  
logfile.setFormatter(formatter)   
logger.setLevel(logging.INFO) 



def get_tickets():
    gt = GateIO(apiKey,secretKey)
    tickers = gt.tickers()
    for k,v in tickers.items():
        t = Tickets_info_history()
        t.name_en = k
        t.starus = 1 if v['result']=="true" else 0
        t.last = float(v['last'])
        t.lowestAsk= float(v['lowestAsk'])
        t.highestBid= float(v['highestBid'])
        t.percentChange= float(v['percentChange'])
        t.baseVolume= float(v['baseVolume'])
        t.quoteVolume= float(v['quoteVolume'])
        t.high24hr= float(v['high24hr'])
        t.low24hr= float(v['low24hr'])
        t.save()

if __name__ == '__main__':
    # get_tickets()
    last_time = time.time()
    while True:
        get_tickets()
        time.sleep(10)
        now_time = time.time()
        if now_time-last_time>3600:
            Monitor.heart_beat_send("tickets ")
            last_time = now_time
            logger.info("get data success!")
        else:
        	logger.info("get data success!")



